import { useRef, useEffect, useState } from "react";
import {
  View,
  Text,
  TextInput,
  Pressable,
  ScrollView,
  KeyboardAvoidingView,
  Platform,
} from "react-native";
import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";
import { fetch as expoFetch } from "expo/fetch";
import { Ionicons } from "@expo/vector-icons";
import { Container } from "@/components/container";
import { Card, useThemeColor } from "heroui-native";

const generateAPIUrl = (relativePath: string) => {
  const serverUrl = process.env.EXPO_PUBLIC_SERVER_URL;
  if (!serverUrl) {
    throw new Error(
      "EXPO_PUBLIC_SERVER_URL environment variable is not defined"
    );
  }
  const path = relativePath.startsWith("/") ? relativePath : `/${relativePath}`;
  return serverUrl.concat(path);
};

export default function AIScreen() {
  const [input, setInput] = useState("");
  const { messages, error, sendMessage } = useChat({
    transport: new DefaultChatTransport({
      fetch: expoFetch as unknown as typeof globalThis.fetch,
      api: generateAPIUrl("/ai"),
    }),
    onError: (error) => console.error(error, "AI Chat Error"),
  });
  const scrollViewRef = useRef<ScrollView>(null);
  const mutedColor = useThemeColor("muted");
  const accentColor = useThemeColor("accent");
  const foregroundColor = useThemeColor("foreground");
  const dangerColor = useThemeColor("danger");

  useEffect(() => {
    scrollViewRef.current?.scrollToEnd({ animated: true });
  }, [messages]);

  const onSubmit = () => {
    const value = input.trim();
    if (value) {
      sendMessage({ text: value });
      setInput("");
    }
  };

  if (error) {
    return (
      <Container>
        <View className="flex-1 justify-center items-center px-4">
          <Card variant="flat" className="p-4 bg-danger/10">
            <Text className="text-danger text-center text-lg mb-2 font-semibold">
              Error: {error.message}
            </Text>
            <Text className="text-muted text-center">
              Please check your connection and try again.
            </Text>
          </Card>
        </View>
      </Container>
    );
  }

  return (
    <Container>
      <KeyboardAvoidingView
        className="flex-1"
        behavior={Platform.OS === "ios" ? "padding" : "height"}
      >
        <View className="flex-1 px-4 py-6">
          <View className="mb-6">
            <Text className="text-foreground text-2xl font-bold mb-2">
              AI Chat
            </Text>
            <Text className="text-muted">
              Chat with our AI assistant
            </Text>
          </View>
          <ScrollView
            ref={scrollViewRef}
            className="flex-1 mb-4"
            showsVerticalScrollIndicator={false}
          >
            {messages.length === 0 ? (
              <View className="flex-1 justify-center items-center">
                <Text className="text-center text-muted text-lg">
                  Ask me anything to get started!
                </Text>
              </View>
            ) : (
              <View className="gap-3">
                {messages.map((message) => (
                  <Card
                    key={message.id}
                    variant={message.role === "user" ? "flat" : "secondary"}
                    className={`p-3 ${
                      message.role === "user"
                        ? "ml-8 bg-accent/10"
                        : "mr-8"
                    }`}
                  >
                    <Text className="text-sm font-semibold mb-1 text-foreground">
                      {message.role === "user" ? "You" : "AI Assistant"}
                    </Text>
                    <View className="gap-1">
                      {message.parts.map((part, i) =>
                        part.type === "text" ? (
                          <Text
                            key={`${message.id}-${i}`}
                            className="text-foreground leading-relaxed"
                          >
                            {part.text}
                          </Text>
                        ) : (
                          <Text
                            key={`${message.id}-${i}`}
                            className="text-foreground leading-relaxed"
                          >
                            {JSON.stringify(part)}
                          </Text>
                        )
                      )}
                    </View>
                  </Card>
                ))}
              </View>
            )}
          </ScrollView>
          <View className="border-t border-divider pt-4">
            <View className="flex-row items-end gap-2">
              <TextInput
                value={input}
                onChangeText={setInput}
                placeholder="Type your message..."
                placeholderTextColor={mutedColor}
                className="flex-1 border border-divider rounded-lg px-3 py-2 text-foreground bg-surface min-h-[40px] max-h-[120px]"
                onSubmitEditing={(e) => {
                  e.preventDefault();
                  onSubmit();
                }}
                autoFocus={true}
              />
              <Pressable
                onPress={onSubmit}
                disabled={!input.trim()}
                className={`p-2 rounded-lg active:opacity-70 ${
                  input.trim() ? "bg-accent" : "bg-surface"
                }`}
              >
                <Ionicons
                  name="send"
                  size={20}
                  color={input.trim() ? foregroundColor : mutedColor}
                />
              </Pressable>
            </View>
          </View>
        </View>
      </KeyboardAvoidingView>
    </Container>
  );
}